package org.hxzon.tapestry5.util;

import org.apache.commons.lang.StringUtils;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.internal.EmptyEventContext;
import org.apache.tapestry5.services.PageRenderRequestParameters;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.linktransform.PageRenderLinkTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SafeAndCssUrlRewriter implements PageRenderLinkTransformer {
    Logger logger = LoggerFactory.getLogger(SafeAndCssUrlRewriter.class);
    private final String pageName;

    public SafeAndCssUrlRewriter(String pageName) {
        this.pageName = pageName;
    }

    public PageRenderRequestParameters decodePageRenderRequest(Request request) {
        String path = request.getPath();
        // delete whitespace
        path = StringUtils.deleteWhitespace(path);
        logger.trace("path incoming:" + path);
        if (path.toLowerCase().contains("web-inf")) {
            logger.warn("path contains web-info,rewrite to root");
            return new PageRenderRequestParameters(pageName, new EmptyEventContext(), false);
        }
//        if (path.contains("/css/") && !path.contains("/assets/")) {
//            path = path.substring(path.indexOf("/css"));
//            logger.trace("path contains css ,rewrite to assets path:" + path);
//            return new PageRenderRequestParameters(TapestryEx.ModulePagePrefix + StaticFileResponse.class.getSimpleName(), new OneStringEventContext(path), false);
//        }
        return null;
    }

    public Link transformPageRenderLink(Link defaultLink, PageRenderRequestParameters parameters) {
        return defaultLink;
    }
}
